from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from backend.models import Article,Cates
from django import forms
from django.http import HttpResponse,HttpResponseRedirect
import logging
# Create your views here.

class ArticleForm(forms.Form):
    cates = Cates.objects.all()
    choice = []
    for i in cates:
        choice.extend([i.id,i.name])
    style = 'form-control'
    title = forms.CharField(
        widget=forms.TextInput(attrs={'class': style, 'name': 'title', 'placeholder': '标题'}),
        label=u"标题",
        max_length=64,
        required=True,
        error_messages={
            'required': u'标题不能为空',
            'max_length': u'标题不能超过64位',
        }
    )
    cid = forms.CharField(label=u'分类')
    content = forms.CharField(label=u"内容")
    head_img = forms.CharField(
        widget=forms.TextInput(attrs={'class': style, 'name': 'head_img', 'placeholder': '图片'}),
        label=u"图片",
        required=True,
        error_messages={
            'required': u'图片不能为空',
        }
    )
@login_required()
def index(request):
    contact_list = Article.objects.all().order_by("id")
    paginator = Paginator(contact_list, 10)
    # 从前端获取当前的页码数,默认为1
    page = request.GET.get('page', 1)
    # 把当前的页码数转换成整数类型
    currentPage = int(page)
    try:
        list = paginator.page(page)
    except PageNotAnInteger:
        list = paginator.page(1)
    except EmptyPage:
        list = paginator.page(paginator.num_pages)
    return render(request, 'backend/article/index.html', locals())

@login_required()
def add(request):
    if request.method == 'POST':
        articleForm = ArticleForm(request.POST)
        if articleForm.is_valid():
            title       = articleForm.cleaned_data['title']
            cid         = articleForm.cleaned_data['cid']
            content     = articleForm.cleaned_data['content']
            head_img    = articleForm.cleaned_data['head_img']
            articlModel = Article(
                title   = title,
                cid     = cid,
                content = content,
                img     = head_img,
            )
            articlModel.save()
            if articlModel.id:
                return HttpResponseRedirect('/backend/article')
            else:
                return render(request, "backend/article/index.html",
                              {"articleForm": articleForm, 'error': '添加失败'})
        else:
            #<ul class="errorlist"><li>cid<ul class="errorlist"><li>This field is required.</li></ul></li><li>content<ul class="errorlist"><li>This field is required.</li></ul></li></ul>
            return render(request, "backend/article/index.html",
                          {"articleForm": articleForm, 'error': articleForm.errors})
    else:
        articleForm = ArticleForm()
        cates = Cates.objects.all()
    return render(request, 'backend/article/add.html', {'articleForm': articleForm, 'cates': cates})

@login_required()
def edit(request, id):
    if request.method == 'POST':
        pass
    else:
        try:
            info = Article.objects.get(id=id)
            cates = Cates.objects.all()
        except Exception as e:
            logger = logging.getLogger('django')
            logger.error(e)
        return render(request, "backend/article/edit.html", {"info": info, 'cates': cates})

@login_required()
def delete(request, id):
    pass